
import 'dart:async';
import 'dart:convert';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_move_page_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/terminal_num_update_event.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_play_time_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_select_terminal_by_pic_page.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_index_service.dart';
import 'package:e_reception_flutter/media_library/media_library_index/service/media_library_video_upload_service.dart';
import 'package:e_reception_flutter/media_library/media_library_index/widgets/add_poster_text_dialog.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/index/bean/index_bind_termainal_info.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/new_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/terminal_by_pic_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_menu_widget/click_back_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/delegate/watermark_text_video_delegate.dart';
import 'package:e_reception_flutter/vg_widgets/vg_photo_preview/vg_photo_preview.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:photo_preview/photo_preview_export.dart';
import 'package:transformer_page_view/transformer_page_view.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

import 'media_select_terminal_page.dart';

///视频、图片设置参数页面
class MediaSettingsPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "MediaSettingsPage";

  static const String INDEX_TOP_INFO_API =ServerApi.BASE_URL + "app/appTerminalManageHome";

  final UploadMediaLibraryItemBean itemBean;
  final List<UploadMediaLibraryItemBean> itemList;
  final bool singleflg;
  final bool needUpload;
  final String hsns;
  final String currentHsn;
  final String branchname;

  const MediaSettingsPage({Key key, this.itemBean, this.singleflg,
    this.needUpload, this.currentHsn, this.hsns, this.itemList, this.branchname}):super(key: key);

  @override
  _MediaSettingsPageState createState() => _MediaSettingsPageState();

  ///跳转方法
  static Future<bool> navigatorPush(
      BuildContext context, UploadMediaLibraryItemBean itemBean,
      {bool singleflg, String hsns,
        List<UploadMediaLibraryItemBean> itemList}) {
    return RouterUtils.routeForFutureResult(
      context,
      MediaSettingsPage(
        itemBean: itemBean,
        singleflg: singleflg,
        hsns: hsns,
        itemList: itemList,
      ),
      routeName: MediaSettingsPage.ROUTER,
    );
  }

  ///跳转方法
  static Future<String> navigatorPushString(
      BuildContext context, UploadMediaLibraryItemBean itemBean,
      {bool singleflg, bool needUpload, String currentHsn, String hsns,
        List<UploadMediaLibraryItemBean> itemList, String branchname}) {
    return RouterUtils.routeForFutureResult(
      context,
      MediaSettingsPage(
        itemBean: itemBean,
        singleflg: singleflg,
        needUpload: needUpload,
        currentHsn: currentHsn,
        hsns: hsns,
        itemList: itemList,
        branchname: branchname,
      ),
      routeName: MediaSettingsPage.ROUTER,
    );
  }
}

class _MediaSettingsPageState extends BaseState<MediaSettingsPage>{

  String _hsns = "";
  String _selectHsns = "";
  String _noHaveHsns = "";
  int _allTerminalSize = 0;
  String startDayStr = "";
  String endDayStr = "";
  DateTime startDay;
  DateTime endDay;
  String playTime = "";
  String interval = "";
  NewTerminalListViewModel _viewModel;
  ValueNotifier<int> _pageValueNotifier;
  TransformerPageController _pageController;
  Key _pageViewKey = UniqueKey();
  static const int LIMIT_LOOP_COUNT = 2000;
  StreamSubscription _terminalNumRefreshSubscription;
  ScrollController _controller;

  double _scale = 1.0;

  //字幕标题
  String _title;
  //字幕内容
  String _content;
  //设置字幕
  bool _addWatermark = true;
  //设置logo
  bool _addLogo = true;
  String _logo;
  String _water;
  MediaLibraryVideoUploadService _mediaLibraryVideoUploadService;
  @override
  void initState() {
    super.initState();
    _mediaLibraryVideoUploadService = MediaLibraryVideoUploadService.getInstance();
    _controller= ScrollController();
    _viewModel = NewTerminalListViewModel(this);

    startDay = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY));
    startDayStr = DateUtil.getDateStrByDateTime(startDay, format: DateFormat.YEAR_MONTH_DAY);
    endDay = DateTime.fromMillisecondsSinceEpoch(startDay.millisecondsSinceEpoch
        + 14*24*3600*1000);
    endDayStr = DateUtil.getDateStrByDateTime(endDay, format: DateFormat.YEAR_MONTH_DAY);
    playTime = DateUtil.formatZHDateTime(startDayStr + " ", DateFormat.ZH_MONTH_DAY, "")  + (DateUtil.isToday(startDay.millisecondsSinceEpoch)?"(今天)":"");
    playTime += " ~ ";
    playTime += DateUtil.formatZHDateTime(endDayStr + " ", DateFormat.ZH_MONTH_DAY, "")  + (DateUtil.isToday(endDay.millisecondsSinceEpoch)?"(今天)":"");
    interval = "15天";
    String cacheKey = UserRepository.getInstance().getHomePunchAndTerminalInfoCacheKey();
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        setState(() {
          Map map = json.decode(jsonStr);
          IndexBindTermainalInfo bean = IndexBindTermainalInfo.fromMap(map);
          if(bean != null){
            if(bean.data != null
                && bean.data.bindTerminalList != null){
              if(!(widget?.singleflg??false)) {
                bean.data.bindTerminalList.forEach((element) {
                  if (!_hsns.contains(element.hsn)) {
                    _hsns += element.hsn;
                    _hsns += ",";
                  }
                });
              }
              _allTerminalSize = bean.data.bindTerminalList.length;
            }
          }
          if(StringUtils.isNotEmpty(_hsns) && _hsns.endsWith(",")){
            _hsns = _hsns.substring(0, _hsns.length-1);
          }
          if(widget?.singleflg??false){
            _hsns = (widget?.hsns??"");
          }
        });
      }
    });

    if(widget?.singleflg??false){
      _hsns = (widget?.hsns??"");
      _viewModel.getTerminalListByPic(context, widget?.itemBean?.id, _hsns);
    }
    _terminalNumRefreshSubscription = VgEventBus.global.streamController.stream.listen((event) {
      if(event is TerminalNumRefreshEvent){
        _allTerminalSize = event?.num??0;
      }
    });
    _pageValueNotifier = ValueNotifier(_getInitPosition());
    ComLogoBean logoBean = UserRepository.getInstance().userData.comLogo;
    if(logoBean != null && StringUtils.isNotEmpty(logoBean.squareTransparentLogo)&& "-1" != logoBean.squareTransparentLogo){
      _logo = logoBean.squareTransparentLogo;
    }else{
      _logo = UserRepository.getInstance().getCompanyLogo();
    }
    //无logo，或者是从单个终端下选择不需要上传的文件
    if(StringUtils.isEmpty(_logo) || (((widget?.singleflg??false) && !(widget?.needUpload??false)))){
      _addLogo = false;
    }

    if(StringUtils.isNotEmpty(widget?.branchname)){
      _water = widget?.branchname;
    }else{
      _water = UserRepository.getInstance().userData.companyInfo.companynick;
    }
  }

  @override
  void dispose() {
    _terminalNumRefreshSubscription?.cancel();
    super.dispose();
  }

  @override
  void didUpdateWidget(MediaSettingsPage oldWidget) {

    Future.delayed(Duration(microseconds: 0), () {
      _pageViewKey = UniqueKey();

      _pageController = TransformerPageController(
        keepPage: true,
        initialPage: _getInitPosition(),
        loop: false,
      );
      _pageValueNotifier?.value = _getInitPosition();
      setState(() {});
    });

    super.didUpdateWidget(oldWidget);

  }

  @override
  Widget build(BuildContext context) {
    _scale = ScreenUtils.screenW(context)/375;
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: Column(
        children: <Widget>[
          _toTopBarWidget(),
          if(widget.singleflg??false) _toPlaceHolderWidget(),
          if(!(widget.singleflg??false)) _showImageListWidget(),
          if(!(widget.singleflg??false)) _toAddTextWidget(),
          // if(!(widget.singleflg??false)) _showImageWidget(),
          if(!(widget.singleflg??false)) _settingsWidget(),
          if(!(widget.singleflg??false)) SizedBox(height: 30,),
          if(!(widget.singleflg??false)) _toConfirmWidget(),
        ],
      ),
    );
  }

  Future<bool> _withdrawFront() async {
    if((widget?.singleflg??false) && !(widget?.needUpload??false)){
      RouterUtils.pop(context);
      return false;
    }
    bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
        title: "提示",
        content: "退出后将不会保存您的操作，确认退出？",
        cancelText: "取消",
        confirmText: "确定",
        confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF());
    if(result ?? false) {
      VgToolUtils.removeAllFocus(context);
      RouterUtils.pop(context);
    }
    return false;
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return WillPopScope(
      onWillPop: _withdrawFront,
      child: VgTopBarWidget(
        isShowBack: true,
        title: (widget?.itemList == null)?"设置":"播放文件·${widget.itemList.length}",
        backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
        navFunction: _withdrawFront,
      ),
    );
  }


  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            errorOnClick: () => _viewModel
                .getTerminalListByPic(context, widget?.itemBean?.id, widget?.hsns),
            loadingOnClick: () => _viewModel
                .getTerminalListByPic(context, widget?.itemBean?.id, widget?.hsns),
            child: child,
          );
        },
        child: _toBodyWidget());
  }

  Widget _toBodyWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.terminalByPicValueNotifier,
        builder: (BuildContext context, TerminalByPicDataBean detailBean, Widget child){
          if(widget?.itemList != null && widget.itemList.length <= 1){
            if(detailBean?.usehsnList != null && (detailBean?.usehsnList?.length??0) > 0){
              if(StringUtils.isNotEmpty(_hsns) && !_hsns.endsWith(",")){
                _hsns += ",";
              }
              detailBean.usehsnList.forEach((element) {
                if(!_hsns.contains(element?.hsn)){
                  _hsns += element?.hsn;
                  _hsns += ",";
                }
              });
              if(StringUtils.isNotEmpty(_hsns) && _hsns.endsWith(",")){
                _hsns = _hsns.substring(0, _hsns.length-1);
              }
              if(StringUtils.isNotEmpty(_selectHsns)){
                _hsns = _selectHsns;
              }
            }

            // if(detailBean.noHavehsnList != null && detailBean.noHavehsnList.length > 0){
            //   detailBean.noHavehsnList.forEach((element) {
            //     if(!_noHaveHsns.contains(element?.hsn)){
            //       _noHaveHsns += element?.hsn;
            //       _noHaveHsns += ",";
            //     }
            //   });
            //   if(StringUtils.isNotEmpty(_noHaveHsns) && _noHaveHsns.endsWith(",")){
            //     _noHaveHsns = _noHaveHsns.substring(0, _noHaveHsns.length-1);
            //   }
            // }
          }
          return Column(
            children: <Widget>[
              _showImageListWidget(),
              Visibility(
                  visible: !(widget?.singleflg??false) || (widget?.needUpload??false),
                  child: _toAddTextWidget()
              ),
              // _showImageWidget(),
              _settingsWidget(),
              SizedBox(height: 30,),
              _toConfirmWidget(),
            ],
          );
        }
    );
  }

  ///横向图片展示栏
  Widget _showImageListWidget(){
    double imageHeight = 251 *_scale;
    return Container(
      padding: EdgeInsets.only(top: 20, bottom: 17),
      decoration: BoxDecoration(
        color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      ),
      child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap:(){
            List<UploadMediaLibraryItemBean> data = new List();
            String _initUrl;
            if(widget?.itemList != null){
              data.addAll(widget?.itemList);
              int index = _pageValueNotifier?.value ?? _getInitPosition();
              _initUrl = widget.itemList.elementAt(index % (widget.itemList.length)).getLocalPicUrl();
            }else{
              data.add(widget?.itemBean);
              _initUrl = widget?.itemBean?.getLocalPicUrl();
            }
            if(widget?.itemList == null || widget.itemList.length == 1){
              if(_addWatermark
                  ||_addLogo
                  || StringUtils.isNotEmpty(_title)
                  || StringUtils.isNotEmpty(_content)){
                VgPhotoPreview.singleWithWatermarkText(context, widget?.itemBean?.localUrl,
                  loadingCoverUrl: widget?.itemBean?.getLocalPicUrl(),
                  loadingImageQualityType: null,
                  type: (widget?.itemBean?.isVideo()??false)?PhotoPreviewType.video:PhotoPreviewType.image,
                  extra: {
                    "id": "",
                    "watermark":_water??"",
                    "waterflg":StringUtils.isNotEmpty(widget?.itemBean?.waterflg??"")?widget?.itemBean?.waterflg:_addWatermark?"01":"00",
                    "logoflg":StringUtils.isNotEmpty(widget?.itemBean?.logoflg??"")?widget?.itemBean?.logoflg:_addLogo?"00":"01",
                    "logo":_logo,
                    "title":StringUtils.isNotEmpty(_title)?_title:(widget?.itemBean?.title??""),
                    "content":StringUtils.isNotEmpty(_content)?_content:(widget?.itemBean?.subtitle??""),
                  },
                );
              }else{
                int count = 0;
                data.forEach((element) {
                  Future<String> tempUrl = WatermarkTextVideoDelegate.transUrl(element.localUrl);
                  tempUrl.then((value){
                    count++;
                    element.localUrl = value;
                    if(count == data.length){
                      VgPhotoPreview.listForPage(
                        context,
                        data,
                        initUrl: _initUrl,
                        urlTrasformFunc: (item) => item?.localUrl,
                        typeTransformFunc: (item) => (item?.isImage())?PhotoPreviewType.image:((item?.isVideo())?PhotoPreviewType.video:PhotoPreviewType.unknow),
                        loadingTransformFunc: (item) => VgPhotoPreview.getImageQualityStr(
                            item.getLocalPicUrl(), ImageQualityType.middleDown),
                        extraTransformFunc: (item) => {
                          "id": "",
                          "watermark":_water??"",
                          "waterflg":StringUtils.isNotEmpty(item?.waterflg??"")?item?.waterflg:_addWatermark?"01":"00",
                          "logoflg":StringUtils.isNotEmpty(item?.logoflg??"")?item?.logoflg:_addLogo?"00":"01",
                          "logo":_logo,
                          "title":StringUtils.isNotEmpty(_title)?_title:(item?.title??""),
                          "content":StringUtils.isNotEmpty(_content)?_content:(item?.subtitle??""),},
                      );
                    }
                  });
                });
              }
            }
          },
          child: _toImageOrImageListViewWidget(imageHeight)
      ),
    );
  }
  ///添加字幕 添加水印
  Widget _toAddTextWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Visibility(
          visible: StringUtils.isNotEmpty(_logo),
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: (){
              setState(() {
                _addLogo = !_addLogo;
              });
            },
            child: Container(
              alignment: Alignment.center,
              width: 80,
              height: 24,
              margin: const EdgeInsets.only(bottom: 20),
              decoration: BoxDecoration(
                color: _addLogo?Color(0x33808388):Color(0x331890FF),
                borderRadius: BorderRadius.circular(15),
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Image.asset(
                    _addLogo?"images/icon_select_watermark.png":"images/icon_unselect_watermark.png",
                    width: 14,
                  ),
                  SizedBox(width: 4,),
                  Text(
                    "添加logo",
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                        color: _addLogo?ThemeRepository.getInstance().getTextMinorGreyColor_808388():ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                        fontSize: 12,
                        height: 1.2
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        SizedBox(width: 10,),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            setState(() {
              _addWatermark = !_addWatermark;
            });
          },
          child: Container(
            alignment: Alignment.center,
            width: 80,
            height: 24,
            margin: const EdgeInsets.only(bottom: 20),
            decoration: BoxDecoration(
              color: _addWatermark?Color(0x33808388):Color(0x331890FF),
              borderRadius: BorderRadius.circular(15),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  _addWatermark?"images/icon_select_watermark.png":"images/icon_unselect_watermark.png",
                  width: 14,
                ),
                SizedBox(width: 4,),
                Text(
                  "添加水印",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: _addWatermark?ThemeRepository.getInstance().getTextMinorGreyColor_808388():ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                      fontSize: 12,
                      height: 1.2
                  ),
                ),
              ],
            ),
          ),
        ),
        SizedBox(width: 10,),
        GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            AddPosterTextDialog.navigatorPushDialog(context,
                title: _title,
                content: _content,
                picSize: widget?.itemList?.length,
                onConfirm: (title, content){
                  setState(() {
                    _title = title;
                    _content = content;
                  });

                },
                onDelete: (){
                  setState(() {
                    _title = "";
                    _content = "";
                  });
                }
            );
          },
          child: Container(
            alignment: Alignment.center,
            width: 80,
            height: 24,
            margin: const EdgeInsets.only(bottom: 20),
            decoration: BoxDecoration(
              color: (StringUtils.isNotEmpty(_title) || StringUtils.isNotEmpty(_content))?Color(
                  0x4D808388):Color(0x331890FF),
              borderRadius: BorderRadius.circular(15),
            ),
            child: Center(
              child: Text(
                (StringUtils.isNotEmpty(_title) || StringUtils.isNotEmpty(_content))?"修改字幕":"+添加字幕",
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
                style: TextStyle(
                    color: (StringUtils.isNotEmpty(_title) || StringUtils.isNotEmpty(_content))?
                    ThemeRepository.getInstance().getTextMinorGreyColor_808388()
                        :ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    fontSize: 12,
                    height: 1.2
                ),
              ),
            ),
          ),
        ),
      ],
    );

  }


  Widget _toImageOrImageListViewWidget(double imageHeight){
    if(widget?.itemList != null && widget.itemList.length > 1){
      return Container(
        alignment: Alignment.center,
        margin: EdgeInsets.symmetric(horizontal: 15),
        height: 214,
        child: GridView.builder(
            itemCount: widget?.itemList?.length ?? 0,
            physics: ClampingScrollPhysics(),
            controller: _controller,
            scrollDirection: Axis.horizontal,
            shrinkWrap: true,
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 1,
              mainAxisSpacing: 10,
              crossAxisSpacing: 0,
              childAspectRatio: 214 / 120,
            ),
            itemBuilder: (BuildContext context, int index) {
              return _toGridItemWidget(imageHeight, context, widget?.itemList?.elementAt(index));
            }),
      );
    }else{
      return _toSingleImageWidget(imageHeight, widget?.itemBean);
    }
  }


  Widget _toGridItemWidget(double imageHeight,
      BuildContext context, UploadMediaLibraryItemBean itemBean) {
    double picWidth = 120*_scale;
    double initialScale = 120/375;
    return ClickBackgroundWidget(
      behavior: HitTestBehavior.opaque,
      onTap: ()async{
        List<UploadMediaLibraryItemBean> data = new List();
        String _initUrl = await WatermarkTextVideoDelegate.transUrl(itemBean.getPicOrVideoUrl());
        if(widget?.itemList != null) {
          data.addAll(widget?.itemList);
          int count = 0;
          data.forEach((element) {
            Future<String> tempUrl = WatermarkTextVideoDelegate.transUrl(element.localUrl);
            tempUrl.then((value) {
              count++;
              element.localUrl = value;
              if(count == widget?.itemList?.length){
                VgPhotoPreview.listForPage(
                  context,
                  data,
                  initUrl: _initUrl,
                  urlTrasformFunc: (item) => item?.localUrl,
                  typeTransformFunc: (item) => (item?.isImage())?PhotoPreviewType.image:((item?.isVideo())?PhotoPreviewType.video:PhotoPreviewType.unknow),
                  loadingTransformFunc: (item) => VgPhotoPreview.getImageQualityStr(
                      item.getLocalPicUrl(), ImageQualityType.middleDown),
                  extraTransformFunc: (item) => {
                    "id": "",
                    "watermark":_water??"",
                    "waterflg":StringUtils.isNotEmpty(item?.waterflg??"")?item?.waterflg:_addWatermark?"01":"00",
                    "logoflg":StringUtils.isNotEmpty(item?.logoflg??"")?item?.logoflg:_addLogo?"00":"01",
                    "logo":_logo,
                    "title":StringUtils.isNotEmpty(_title)?_title:(item?.title??""),
                    "content":StringUtils.isNotEmpty(_content)?_content:(item?.subtitle??""),},
                );
              }
            });
          });
        }
      },
      child: ClipRRect(
        child: Container(
          decoration: BoxDecoration(color: Colors.black),
          child: Stack(
            alignment: Alignment.center,
            children: <Widget>[
              VgCacheNetWorkImage(
                itemBean?.getLocalPicUrl() ?? "",
                fit: BoxFit.cover,
                imageQualityType: ImageQualityType.middleDown,
              ),
              Center(
                child: Offstage(
                    offstage: !(itemBean?.isVideo() ?? false),
                    child: Opacity(
                      opacity: 0.5,
                      child: Image.asset(
                        "images/video_play_ico.png",
                        width: 52,
                      ),
                    )),
              ),
              Align(
                alignment: Alignment.topRight,
                child: Visibility(
                  visible: StringUtils.isNotEmpty(_logo) && (_addLogo || "00" == itemBean.logoflg),
                  child: _toLogoWidget(initialScale),
                ),
              ),
              Align(
                alignment: Alignment.bottomCenter,
                child: Visibility(
                  visible: _addWatermark || StringUtils.isNotEmpty(_title) || StringUtils.isNotEmpty(_content),
                  child: _toTextWidget(picWidth, initialScale, itemBean),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _toSingleImageWidget(double imageHeight, UploadMediaLibraryItemBean itemBean){
    double _fixScale = 9/16;
    double picHeight = 213;
    double picWidth = 120;
    double initialScale = 120/375;
    VgCacheNetWorkImage image;
    double textWidth;
    if(itemBean.folderWidth > itemBean.folderHeight){
      //高度大，固定宽度
      picHeight = picHeight*_scale;
      picWidth = picWidth*_scale;
      image = VgCacheNetWorkImage(
          itemBean?.getLocalPicUrl() ?? "",
          imageQualityType: ImageQualityType.high,
          fit: BoxFit.cover,
          width: picWidth,
          placeWidget: Container(color: Colors.black,)
      );
      textWidth = picWidth;
    }else{
      picHeight = picHeight*_scale;
      if(itemBean.folderWidth/itemBean.folderHeight < _fixScale){
        picWidth = picWidth*_scale;
      }else{
        picWidth =  picHeight*_fixScale;
      }
      image = VgCacheNetWorkImage(
          itemBean?.getLocalPicUrl() ?? "",
          imageQualityType: ImageQualityType.high,
          fit: BoxFit.cover,
          width: picWidth,
          placeWidget: Container(color: Colors.black,)
      );
      textWidth = picWidth;
    }
    return Container(
      height: picHeight,
      width: picWidth,
      color: Colors.black,
      child: Stack(
        alignment: Alignment.center,
        children: [
          image,
          Offstage(
            offstage: !(itemBean?.isVideo() ?? false),
            child: Opacity(
              opacity: 0.5,
              child: Image.asset(
                "images/video_play_ico.png",
                width: 37,
              ),
            ),
          ),
          Align(
            alignment: Alignment.topRight,
            child: Visibility(
              visible: _addLogo && StringUtils.isNotEmpty(_logo),
              child: _toLogoWidget(initialScale),
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Visibility(
              visible: _addWatermark || StringUtils.isNotEmpty(_title) || StringUtils.isNotEmpty(_content),
              child: _toTextWidget(textWidth, initialScale, itemBean),
            ),
          ),
        ],
      ),
    );
  }

  Widget _toLogoWidget(double scale){
    scale = scale > 1?1:scale;
    return Container(
      margin: EdgeInsets.all(21*scale),
      child: Stack(
        alignment: Alignment.center,
        children: [
          Container(
            width: 48*scale,
            height: 48*scale,
            decoration: BoxDecoration(
                color: Color(0x4DFFFFFF),
                borderRadius: BorderRadius.circular(7*scale)
            ),
          ),
          ClipRRect(
            borderRadius: BorderRadius.circular(4*scale),
            child: Container(
              decoration: BoxDecoration(color: Colors.white),
              child: VgCacheNetWorkImage(
                _logo,
                width: 42*scale,
                height: 42*scale,
                fit: BoxFit.contain,
                imageQualityType: ImageQualityType.middleUp,
                defaultPlaceType: ImagePlaceType.head,
                defaultErrorType: ImageErrorType.head,
              ),
            ),
          )
        ],
      ),
    );
  }

  Widget _toTextWidget(double width, double scale, UploadMediaLibraryItemBean itemBean){
    bool tempWatermark = _addWatermark;
    String tempTitle = _title;
    String tempContent = _content;
    if((widget?.singleflg??false) && !(widget?.needUpload??false)){
      tempWatermark = ("01" == itemBean.waterflg);
      tempTitle = itemBean.title??"";
      tempContent = itemBean.subtitle??"";
    }
    scale = scale > 1?1:scale;
    return Container(
      padding: EdgeInsets.symmetric(horizontal: scale*12),
      width: width>ScreenUtils.screenW(context)?ScreenUtils.screenW(context):width,
      decoration: (StringUtils.isNotEmpty(tempTitle) || StringUtils.isNotEmpty(tempContent))? BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Color(0x00000000),
                Color(0x66000000),
              ]
          )
      ): BoxDecoration(),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Visibility(
            visible: tempWatermark,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  alignment: Alignment.center,
                  height: scale*24,
                  padding: EdgeInsets.only(left: scale*6, right: scale*12),
                  decoration: BoxDecoration(
                    color: Color(0x1A000000),
                    borderRadius: BorderRadius.circular(scale*12),
                    border: Border.all(
                        color: Colors.white,
                        width: 0.2),
                  ),
                  child: Text(
                    "· ${_water??""}",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: scale * 14,
                        height: 1.12
                    ),
                  ),
                ),
              ],
            ),
          ),
          SizedBox(height: tempWatermark?scale*6:scale*30,),
          Visibility(
            visible: StringUtils.isNotEmpty(tempTitle),
            child: Text(
              tempTitle??"",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: scale*20,
                  fontWeight: FontWeight.w600,
                  height: 1.3
              ),
            ),
          ),
          Visibility(
              visible: StringUtils.isNotEmpty(tempTitle),
              child: SizedBox(height: scale*4,)
          ),
          Visibility(
            visible: StringUtils.isNotEmpty(tempContent),
            child: Text(
              tempContent??"",
              style: TextStyle(
                  color: Colors.white,
                  fontSize: scale*14,
                  height: 1.42
              ),
            ),
          ),
          SizedBox(height: (tempWatermark && StringUtils.isEmpty(tempContent))?scale*6:scale*12,),
        ],
      ),
    );
  }

  ///初始化位置
  int _getInitPosition() {
    int initIndex = 0;
    return ((widget?.itemList?.length ?? 0) * LIMIT_LOOP_COUNT / 2).floor() + initIndex;
  }

  ///播放终端、播放天数
  Widget _settingsWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Column(
        children: <Widget>[
          _playTerminalWidget(),

          _playTimes(),

        ],
      ),
    );
  }



  ///播放终端
  Widget _playTerminalWidget(){
    String terminalHint = "";
    int selectedSize = StringUtils.isEmpty(_hsns)?0:_hsns.split(",").length;
    if(_allTerminalSize != 0){
      if(selectedSize == _allTerminalSize){
        terminalHint = "全部$selectedSize台终端";
      }else if(selectedSize == 0){
        terminalHint = "暂不选择终端";
      }else{
        terminalHint = "$selectedSize台终端";
      }
    }

    return Visibility(
      visible: (widget?.singleflg??false)?((widget?.itemList?.length??0) <= 1):(_allTerminalSize != 0),
      child: Column(
        children: [
          GestureDetector(
            onTap: () async{
              if(widget?.singleflg??false){
                String tempHsns = StringUtils.isEmpty(_selectHsns)?_hsns:_selectHsns;
                String hsns = await MediaSelectTerminalByPicPage.navigatorPush(context, currentHsn: widget?.currentHsn,
                    hsns: tempHsns.replaceAll("${widget?.currentHsn},", ""), picid: widget?.itemBean?.id);
                if(hsns != null){
                  setState(() {
                    if(StringUtils.isNotEmpty(hsns)){
                      hsns += ",";
                    }
                    hsns += widget?.currentHsn;
                    _hsns = hsns;
                    _selectHsns = hsns;
                  });
                }
              }else{
                String hsns = await MediaSelectTerminalPage.navigatorPush(context, hsns: _hsns);
                if(hsns != null){
                  setState(() {_hsns = hsns;});
                }
              }

            },
            child: Container(
              height: 50,
              padding: EdgeInsets.symmetric(horizontal: 15),
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              child: Row(
                children: <Widget>[
                  Text(
                    "播放终端",
                    style: TextStyle(
                      fontSize: 14,
                      color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                    ),
                  ),
                  Spacer(),
                  Row(
                    children: <Widget>[
                      Text(
                        terminalHint,
                        style: TextStyle(
                          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                          fontSize: 14,
                          height: 1.2,
                        ),
                      ),
                      SizedBox(width: 9,),
                      Image.asset(
                        "images/index_arrow_ico.png",
                        width: 6,
                      )
                    ],
                  ),
                ],
              ),
            ),
          ),
          Visibility(
              visible: selectedSize != 0,
              child: _toSplitLineWidget()
          ),
        ],
      ),
    );
  }

  ///播放天数
  Widget _playTimes(){
    int selectedSize = StringUtils.isEmpty(_hsns)?0:_hsns.split(",").length;
    return Visibility(
      visible: selectedSize != 0,
      child: Column(
        children: [
          GestureDetector(
            onTap: () async{
              Map<String, dynamic> resultMap = await MediaPlayTimePage.navigatorPush(context, startDay: startDay, endDay: endDay);
              if(resultMap == null){
                return;
              }
              setState(() {
                startDayStr = resultMap[MediaPlayTimePage.RESULT_START_DAY_STR];
                endDayStr = resultMap[MediaPlayTimePage.RESULT_END_DAY_STR];
                startDay = resultMap[MediaPlayTimePage.RESULT_START_DAY];
                endDay = resultMap[MediaPlayTimePage.RESULT_END_DAY];

                playTime = DateUtil.formatZHDateTime(startDayStr + " ", DateFormat.ZH_MONTH_DAY, "")  + (DateUtil.isToday(startDay.millisecondsSinceEpoch)?"(今天)":"");
                if(endDay == null){
                  playTime += " ~ ";
                  playTime += "永久";
                  interval = "永久";
                }else if(startDayStr != endDayStr){
                  playTime += " ~ ";
                  playTime += DateUtil.formatZHDateTime(endDayStr + " ", DateFormat.ZH_MONTH_DAY, "");
                  interval = (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1).toString() + "天";
                }else {
                  interval = (((endDay.millisecondsSinceEpoch - startDay.millisecondsSinceEpoch)~/(1000*3600*24)) + 1).toString() + "天";
                }

                print(MediaSettingsPage.ROUTER + ":" + startDayStr);
                print(MediaSettingsPage.ROUTER + ":" + endDayStr);
              });
            },
            child: Container(
              height: 64,
              padding: EdgeInsets.symmetric(horizontal: 15),
              color: ThemeRepository.getInstance().getCardBgColor_21263C(),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: [
                      Text(
                        "播放天数",
                        style: TextStyle(
                          fontSize: 14,
                          height: 1.2,
                          color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
                        ),
                      ),
                      Spacer(),
                      Row(
                        children: <Widget>[
                          Text(
                            interval,
                            style: TextStyle(
                              color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                              fontSize: 14,
                              height: 1.2,
                            ),
                          ),
                          SizedBox(width: 9,),
                          Image.asset(
                            "images/index_arrow_ico.png",
                            width: 6,
                          )
                        ],
                      ),

                    ],
                  ),
                  Text(
                    playTime,
                    style: TextStyle(
                      fontSize: 11,
                      height: 1.2,
                      color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    ),
                  ),
                ],
              ),
            ),
          ),
          // SizedBox(height: 14,)
        ],
      ),
    );
  }

  ///分割线
  Widget _toSplitLineWidget() {
    return Container(
      height: 0.5,
      margin: const EdgeInsets.only(left: 15, right: 0),
      color: ThemeRepository.getInstance().getLineColor_3A3F50(),
    );
  }

  ///确定
  Widget _toConfirmWidget(){
    return CommonFixedHeightConfirmButtonWidget(
      isAlive: true,
      height: 40,
      margin: const EdgeInsets.symmetric(horizontal: 15),
      unSelectBgColor: Color(0xFF3A3F50),
      selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
      unSelectTextStyle: TextStyle(
        color: VgColors.INPUT_BG_COLOR,
        fontSize: 15,
      ),
      selectedTextStyle: TextStyle(
        color: Colors.white,
        fontSize: 15,
        // fontWeight: FontWeight.w600
      ),
      text: "确定",
      onTap: (){
        _doConfirm();
      },
    );
  }

  int _getSelectedCount(List<NewTerminalListItemBean> data){
    int count = 0;
    if(data != null){
      data.forEach((element) {
        if(element.selectStatus??false){
          count++;
        }
      });
    }
    return count;
  }

  String getPicid(){
    String picid = "";
    if(widget?.itemList != null){
      widget?.itemList?.forEach((element) {
        picid += element.id;
        picid += ",";
      });
      if(StringUtils.isNotEmpty(picid) && picid.endsWith(",")){
        picid = picid.substring(0, picid.length-1);
      }
    }else{
      picid = widget?.itemBean?.id;
    }
    return picid;
  }

  _doConfirm(){
    //是否需要跳转到待播列表
    //如果当前传的数据开始日期在当前日期之后就需要跳转
    bool needPopToWait = false;
    DateTime currentDay = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY));
    if(currentDay.millisecondsSinceEpoch < (startDay?.millisecondsSinceEpoch??0)){
      needPopToWait = true;
    }
    if(widget.singleflg??false){
      if(widget?.needUpload??false){
        _doUpload(needPopToWait);
      }else{
        String tempHsns = _hsns;
        if(StringUtils.isNotEmpty(_noHaveHsns)){
          tempHsns = tempHsns + "," + _noHaveHsns;
        }
        if(getPicid().split(",").length > 1){
          _viewModel.addMediaListToTerminal(context,
              startDayStr, endDayStr, tempHsns, getPicid(), needPopToWait: needPopToWait);
        }else{
          _viewModel.addMediaToTerminals(context,
              StringUtils.isEmpty(tempHsns)?"00"
                  :((_allTerminalSize == tempHsns.split(",").length)?"01":"00"),
              startDayStr, endDayStr, tempHsns, getPicid(), needPopToWait: needPopToWait);
        }
      }
    }else{
      _doUpload(needPopToWait);
    }
  }

  _doUpload(bool needPopToWait){
    List<UploadMediaLibraryItemBean> uploadList = List();
    if(widget?.itemList != null && widget.itemList.isNotEmpty){
      uploadList.addAll(widget?.itemList);
    }else{
      uploadList.add(widget?.itemBean);
    }
    String tempHsns = _hsns;
    if(StringUtils.isNotEmpty(_noHaveHsns)){
      tempHsns = tempHsns + "," + _noHaveHsns;
    }
    if(uploadList.length == 1 && uploadList.elementAt(0).isVideo()){
      _mediaLibraryVideoUploadService.upload(uploadList?.elementAt(0),
          tempHsns, startDayStr, endDayStr,
          StringUtils.isEmpty(tempHsns)?"00"
              :((_allTerminalSize == tempHsns.split(",").length)?"01":"00"),
          _title, _content, _addWatermark?"01":"00", _addLogo?"00":"01");
      VgToastUtils.toast(context, "已发送");
      if(needPopToWait){
        VgEventBus.global.send(new MediaMovePageEvent(2));
      }
      if(widget?.needUpload??false){
        RouterUtils.pop(context, result: "添加成功");
      }else{
        RouterUtils.popUntil(context, AppMain.ROUTER,);
      }
      return;
    }
    MediaLibraryIndexService service =
    MediaLibraryIndexService().setListAndSettings(
        context, uploadList, tempHsns,
        StringUtils.isEmpty(tempHsns)?null:startDayStr,
        StringUtils.isEmpty(tempHsns)?null:endDayStr,
        StringUtils.isEmpty(tempHsns)?"00"
            :((_allTerminalSize == tempHsns.split(",").length)?"01":"00"),
        title: _title,
        content: _content,
        waterflg: _addWatermark?"01":"00",
        logoflg: _addLogo?"00":"01"
    );

    if (service != null) {
      VgHudUtils.show(context, "正在上传");
      if(uploadList.length > 1){
        //多图上传
        service.multiUpload(VgBaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgHudUtils.hide(AppMain.context);
          VgToastUtils.toast(AppMain.context, "上传完成");
          VgEventBus.global.send(new MediaLibraryRefreshEven());
          if(needPopToWait){
            VgEventBus.global.send(new MediaMovePageEvent(2));
          }
          if(widget?.needUpload??false){
            RouterUtils.pop(context, result: "添加成功");
          }else{
            RouterUtils.popUntil(context, AppMain.ROUTER,);
          }
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgHudUtils.hide(AppMain.context);
          print("MediaSettingsPage上传失败:" + msg);
          VgToastUtils.toast(AppMain.context, "上传失败");
        }));
      }else{
        //单文件上传
        service.upload(VgBaseCallback(onSuccess: (val) {
          VgHudUtils.hide(context);
          VgHudUtils.hide(AppMain.context);
          print("MediaSettingsPage上传完成1:");
          VgToastUtils.toast(AppMain.context, "上传完成");
          VgEventBus.global.send(new MediaLibraryRefreshEven());
          if(needPopToWait){
            VgEventBus.global.send(new MediaMovePageEvent(2));
          }
          if(widget?.needUpload??false){
            RouterUtils.pop(context, result: "添加成功");
          }else{
            RouterUtils.popUntil(context, AppMain.ROUTER,);
          }
        }, onError: (msg) {
          VgHudUtils.hide(context);
          VgHudUtils.hide(AppMain.context);
          print("MediaSettingsPage上传失败1:" + msg);
          VgToastUtils.toast(AppMain.context, "上传失败");
        }));
      }


    }


  }

}